package cn.xuchunh;

/**
 * Created by XuChunH on 2016/3/14.
 */
public class QuickSortOld {

    public static void main(String[] args) {
        int[] source = new int[]{1,2,3,4,5,6,7,8,9};
        sort2(source, 0, source.length - 1);
        for (int item : source) {
            System.out.print(item + "\t");
        }
    }

    public void sort(int arr[], int low, int high) {
        int l = low;
        int h = high;
        int povit = arr[low];

        while (l < h) {
            while (l < h && arr[h] >= povit)
                h--;
            if (l < h) {
                int temp = arr[h];
                arr[h] = arr[l];
                arr[l] = temp;
                l++;
            }

            while (l < h && arr[l] <= povit)
                l++;

            if (l < h) {
                int temp = arr[h];
                arr[h] = arr[l];
                arr[l] = temp;
                h--;
            }
        }
        for (int item : arr) {
            System.out.print(item + " ");
        }
        System.out.println();
        System.out.print("l=" + (l + 1) + "h=" + (h + 1) + "povit=" + povit + "\n");
        if (l > low) {
            sort(arr, low, l - 1);
        }
        if (h < high) {
            sort(arr, l + 1, high);
        }
    }

    public static void sort2(int[] source, int left, int right) {
        if (left < right) {
            int key = source[left];
            int i = left;
            int j = right;
            while (i < j) {
                while (j > i && source[j] >= key) {
                    j--;
                }
                if (j > i) {
                    source[i++] = source[j];
                }
                while (j > i && source[i] <= key) {
                    i++;
                }
                if (j > i) {
                    source[j--] = source[i];
                }
            }
            source[i] = key;
            sort2(source, left, i - 1);
            sort2(source, j + 1, right);
        }

    }

}
